package addition.nio;

import addition.utils.FileUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class BlockingNioDemo2 {

    @Test
    public void server() throws IOException {
        final ServerSocketChannel ssChannel = ServerSocketChannel.open();
        ssChannel.bind(new InetSocketAddress(8080));

        final FileChannel outChannel = FileChannel.open(Paths.get("receive.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        final ByteBuffer buf = ByteBuffer.allocate(1024);

        final SocketChannel sChannel = ssChannel.accept();
        while (sChannel.read(buf) != -1) {
            buf.flip();
            outChannel.write(buf);
            buf.clear();
        }

        // 结束输入
        sChannel.shutdownInput();

        // 输出反馈
        buf.clear();
        buf.put("接收成功".getBytes());
        buf.flip();
        sChannel.write(buf);

        outChannel.close();
        sChannel.close();
        ssChannel.close();
    }

    @Test
    public void client() throws IOException {
        final SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));

        final FileChannel inChannel = FileChannel.open(Paths.get(FileUtils.getRootFilePath("wallhaven-z85gyw.jpg")), StandardOpenOption.READ);
        final ByteBuffer buf = ByteBuffer.allocate(1024);

        while (inChannel.read(buf) != -1) {
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }

        // 结束输出
        sChannel.shutdownOutput();

        // 读取服务端反馈
        int len;
        buf.clear();
        while ((len = sChannel.read(buf)) != -1) {
            buf.flip();
            System.out.println(new String(buf.array(), 0, len));
            buf.clear();
        }

        inChannel.close();
        sChannel.close();
    }


}
